import React, { useState, useEffect } from 'react'
import louyu from '../assets/css/louyu.module.css'
import { Table, Switch, Image, Modal, message } from 'antd';
import del from '../assets/images/delete.png'
import edit from '../assets/images/edit.png'
import AddBuild from '../action/AddBuild';
import cont from '../assets/js/cont'
import axios from '../axios/index';
import DetailBuild from '../action/DetailBuild';

export default function Build() {
  let [show, setShow] = useState(false)
  let [showDetail, setShowDetail] = useState(false)
  let [dataSource, setDataSource] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [id, setId] = useState(0)
  let [info, setInfo] = useState([])
  let [name, setName] = useState('')
  let [list, setList] = useState([])
  let [showlist, setShowlist] = useState(true)

  const handleOk = () => {
    setIsModalOpen(false);
    axios.delete('/api/build/delete', {
      params: {
        id: id
      }
    }).then((res) => {
      getData()
      success()
    })
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };


  function getImg(url) {
    return new URL(url, import.meta.url).href
  }

  let getData = () => {
    axios.get('/api/build').then((res) => {
      console.log(res.data);
      setDataSource([...res.data])
    })
  }

  useEffect(() => {
    getData()
  }, [])

  let deleteBuild = (id) => {
    setIsModalOpen(true)
    setId(id)
  }

  const detailBuild = (id) => {
    axios.get('/api//build/info', {
      params: {
        id: id
      }
    }).then((res) => {
      setInfo(res.data)
      setShowDetail(true)
    })
  }

  const search = () => {
    setShowlist(false)
    axios.get('/api/build/name', {
      params: {
        name: name
      }
    }).then((res) => {
      setList(res.data)
    })
  }

  const reset = () => {
    setName('')
    setShowlist(true)
  }

  const columns = [
    {
      title: '名称',
      key: 'name',
      render: (row) => {
        return (
          <span className={louyu.name} style={{
            cursor:'pointer'
          }}>
            <Image src={getImg(row.img)} alt="" width={45} height={60}
            />
            <span onClick={() => {
              detailBuild(row.id)
            }}>{row.name}</span>
          </span>
        )

      }
    },
    {
      title: '详细地址',
      dataIndex: 'addr',
      key: 'addr',
    },
    {
      title: '操作',
      key: 'action',
      render: (row) => (
        <span>
          <img src={edit} alt="" className={louyu.edit} />
          <img src={del} alt="" className={louyu.del}
            onClick={() =>
              deleteBuild(row.id)
            }
          />
        </span>
      ),
    },
  ]

  const itemRender = (page, type, originalElement) => {
    if (type === 'prev') {
      return;
    }
    if (type === 'next') {
      return <a>下一页</a>;
    }

    return originalElement;
  };

  const success = () => {
    message.open({
      type: 'success',
      content: '楼宇删除成功！'
    });
  };

  return (
    <cont.Provider
      value={{
        change: () => {
          setShow(false)
        },
        changeDetail: () => {
          setShowDetail(false)
        }
      }}
    >
      <div className={louyu.louyu}>
        <button className={louyu.add} onClick={() => {
          setShow(true)
        }}>新建楼宇</button>
        {dataSource.length > 0 ?
          <div>
            <div className={louyu.search}>
              <input type="text" placeholder='请输入楼宇名称' value={name} onChange={(e) => { setName(e.target.value) }} />
              <button className={louyu.tosearch} onClick={() => { search() }}>查询</button>
              <button className={louyu.reset} onClick={() => {
                reset()
              }}>重置</button>
            </div>
            <div className={louyu.table}>
              <Table
                dataSource={showlist ? dataSource : list}
                columns={columns}
                pagination={{
                  pageSize: 5, // 每页显示5条数据
                  total:showlist ? dataSource.length : list.length, // 总数据条数
                  showTotal: (total, range) => `共${total}条记录,每页${range[1] - range[0] + 1}条`,
                  itemRender, // 使用自定义的分页器渲染
                  showQuickJumper: true, // 启用快速跳转
                }}
              />

            </div>
            <Modal title="此操作是不可恢复的！" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
              okText="确认"
              cancelText="取消"
            >
              <p>您确认要执行此删除操作吗?</p>
            </Modal>
          </div>
          : <div className={louyu.weit}>
            <img src={getImg('../assets/images/weit.png')} alt="" />
            <div>项目下未创建楼宇～</div>
          </div>
        }

      </div>
      {show && <AddBuild getData={getData}></AddBuild>}
      {showDetail && <DetailBuild info={info} getData={getData}></DetailBuild>}
    </cont.Provider>
  )
}

